#include "SimpleHighscoreService.h"
#include <stdio.h>
#include <fstream>
#include "utils\Log.h"

void SimpleHighscoreService::initialize() {
	readHighscores();
}

void SimpleHighscoreService::setScore(uint32 score,uint32 level,uint32 timer) {
	for ( int i = 0; i < m_TotalScores; ++i ) {
		Score* s = &m_Scores[i];
		if ( s->level == level && s->timer == timer ) {
			if ( score > s->points ) {
				s->points = score;
			}
		}
	}
}

uint32 SimpleHighscoreService::getScore(uint32 level,uint32 timer) {
	LOG(logINFO) << "getting highscore for " << level << " " << timer << " " << m_TotalScores;
	for ( int i = 0; i < m_TotalScores; ++i ) {
		Score* s = &m_Scores[i];
		if ( s->level == level && s->timer == timer ) {
			return s->points;
		}
	}
	return 0;
}

void SimpleHighscoreService::readHighscores() {
	m_TotalScores = 0;
	LOG(logINFO) << "reading score.his";
	std::fstream binary_file("score.his", std::ios::binary | std::ios::in);    
    if (binary_file.is_open()) {
		binary_file.read((char*)&m_TotalScores, sizeof (int));
		LOG(logINFO) << "number of score entries " << m_TotalScores;
		for ( int i = 0; i < m_TotalScores; ++i ) {
			Score s;
			binary_file.read((char*)&s, sizeof (Score));
			m_Scores.push_back(s);
		}
		binary_file.close();
    }
	else {
		LOG(logINFO) << "no file found";
	}    
}

void SimpleHighscoreService::saveHighscores() {
	LOG(logINFO) << "saving highscore " << m_TotalScores;
	std::fstream binary_file("score.his", std::ios::out | std::ios::binary);    
	binary_file.write(reinterpret_cast<char *> (&m_TotalScores), sizeof (int));    
	for ( int i = 0; i < m_TotalScores; ++i ) {
		Score* s = &m_Scores[i];
		binary_file.write(reinterpret_cast<char *> (s), sizeof (Score));    
	}
    binary_file.close();
}

